package utils

import (
	"regexp"
	"strconv"
	"strings"
)

//256 system
//256 进制
var ipw = []int{256 * 256 * 256, 256 * 256, 256, 1}

func intToIP(ipnum int) string {
	var result string
	tmp := ipnum
	tmpip := tmp / ipw[0]
	result = strconv.Itoa(tmpip)
	tmp = tmp % ipw[0]
	for i := 1; i < 4; i++ {
		tmpip := tmp / ipw[i]
		result = result + "." + strconv.Itoa(tmpip)
		tmp = tmp % ipw[i]
	}

	return result
}

func ipToInt(ipstr string) int {
	str := strings.Split(ipstr, ".")
	result := 0
	for i := 0; i < 4; i++ {
		temp, _ := strconv.Atoi(str[i])
		result = result + temp*ipw[i]
	}
	return result
}

//192.168.1.1-255:90-100
//192.168.1.1-255:90,80,70
//192.168.1.1-255
//192.168.1.1,2,3
//return [192.168.1.1,..,192.168.1.255],255
//if some err return nil,a 0
func SplitIp(ipport string) ([]string, int) {
	ips := strings.Split(ipport, ":")[0]
	ip := strings.Split(ips, "-")
	if len(ip) > 1 {
		ipR := strings.Split(ip[1], ".")
		ipL := strings.Split(ip[0], ".")
		lenipR := len(ipR)
		ipLInt := ipToInt(ip[0])

		ipRInt := 0
		for i := 0; i < 4-lenipR; i++ {
			temp, _ := strconv.Atoi(ipL[i])
			ipRInt = ipRInt + temp*ipw[i]
		}
		for i := 4 - lenipR; i < 4; i++ {
			temp, _ := strconv.Atoi(ipR[i+lenipR-4])
			ipRInt = ipRInt + temp*ipw[i]
		}

		var lenRe = ipRInt - ipLInt + 1
		if lenRe <= 0 {
			return nil, 0
		}
		var result = make([]string, lenRe)
		for i := ipLInt; i <= ipRInt; i++ {
			result[i-ipLInt] = intToIP(i)
		}
		return result, lenRe
	}
	ip = strings.Split(ips, ",")
	lenip := len(ip)
	if lenip == 1 {
		return ip, 1
	}

	regex := regexp.MustCompile("^\\d{1,3}.\\d{1,3}.\\d{1,3}")
	ip3 := regex.FindString(ip[0])
	for i := 1; i < lenip; i++ {
		ip[i] = ip3 + "." + ip[i]
	}
	return ip, lenip
}
